package zezutom.joker.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * A joker tells jokes. Telling a bad joke proves lethal to him.
 * 
 * @author tomasz
 */
@Entity
@Table(name="jokers")
public class Joker implements Serializable {
    
    public static final String TO_STRING_FORMAT = "%s, %s";
    
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
        
    @Column(name="joker_name")
    private String name;
    
    @Column
    @Enumerated(EnumType.STRING)
    private Popularity popularity;
    
    @OneToMany(cascade= CascadeType.ALL, mappedBy="joker")
    private Collection<Joke> jokes;

    public Joker() {}
    
    public Joker(String name, Popularity popularity) {
        this.name = name;
        this.popularity = popularity;
    }

    public Long getId() {
        return id;
    }
        
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Popularity getPopularity() {
        return popularity;
    }

    public void setPopularity(Popularity popularity) {
        this.popularity = popularity;
    }        
    
    public Collection<Joke> getJokes() {
        return (jokes != null) ? Collections.unmodifiableCollection(jokes) : null;
    }
    
    public void addJoke(Joke joke) {
        if (jokes == null) {
            jokes = new ArrayList<Joke>();
        }
        joke.setJoker(this);
        jokes.add(joke);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Joker other = (Joker) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.popularity != other.popularity) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 23 * hash + (this.popularity != null ? this.popularity.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return String.format(TO_STRING_FORMAT, name, popularity);
    }
        
}
